package cn.jhz.learn.community_dynamic.security.handler;

import cn.jhz.learn.community_dynamic.common.GLOBAL;
import cn.jhz.learn.community_dynamic.common.bean.JsonData;
import cn.jhz.learn.community_dynamic.security.helper.LoginHelper;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class HttpStatusLoginFailureHandler implements AuthenticationFailureHandler {

    
    private final ObjectMapper mapper;
    
    @Autowired
    public HttpStatusLoginFailureHandler(ObjectMapper mapper) {
	super();
	this.mapper = mapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("UTF-8");

        System.out.println("======================================");
        
        String jsonStr = mapper.writeValueAsString(JsonData.newFailInstance(GLOBAL.STATUS_CODE.BAD_REQUEST, exception.getMessage()));
        try(PrintWriter writer = response.getWriter()){
            writer.print(jsonStr);
        }
        LoginHelper.clear();
    }
}
